package com.java.base.exercise.current;

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @Author RenPu
 * @Date 2021/9/29 17:52
 * @Version 1.0
 * @Description:
 **/
public class ForkJoinPoolDemo1 {

    public static void main(String[] args) {

        Integer invoke = new ForkJoinPool().invoke(new CountingTask(Paths.get("D:/logs")));
        System.out.println("D盘 software文件下的总数为：" + invoke);
        System.out.println("Main  Thread  End ! ! !");

    }


    static class CountingTask extends RecursiveTask<Integer> {

        private Path dir;

        public CountingTask(Path dir) {
            this.dir = dir;
        }

        public CountingTask() {

        }


        @Override
        protected Integer compute() {
            Integer count = 0;
            ArrayList<CountingTask> countingTasks = new ArrayList<>();
            try {
                DirectoryStream<Path> paths = Files.newDirectoryStream(dir);
                for (Path path : paths) {
                    if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
                        countingTasks.add(new CountingTask(path));
                    } else {
                        count++;
                    }
                }
                if (!countingTasks.isEmpty()) {
                    for (CountingTask countingTask : invokeAll(countingTasks)) {
                        count += countingTask.join();
                    }

                }
            } catch (IOException e) {
                return 0;
            }
            return count;
        }
    }


}
